import Router from 'koa-router'
import FormData from 'form-data'
import * as fs from "fs";
import request from "../utils/request";
import config from '../project.config.json'
import path from "path";

const router = new Router()

const database = {
  '392d477dadd47061d14b77c9a6dc2053': 'ihty9ifvfih'
}

router.post('/upload', async context => {
  const form = new FormData()
  const file = context.request.files.file
  const md5 = context.request.body.md5
  if (!md5) {
    context.status = 500
    context.body = 'md5 不能为空'
    return
  }
  if (database[md5]) {
    context.body = database[md5]
    return
  }

  const ext = path.extname(file.name);
  const basename = path.basename(file.name, ext)
  const suffixName = `${basename}${ext.toLowerCase()}${config.suffix}`

  form.append('task', '1')
  form.append('ve', '2')
  form.append('lastModifiedDate', file.lastModifiedDate.toString())
  form.append('type', 'application/octet-stream')
  form.append('id', 'WU_FILE_0')
  form.append('folder_id_bb_n', '2555906')
  form.append('size', file.size)
  form.append('name', suffixName)
  form.append('upload_file', fs.createReadStream(file.path), suffixName)

  const value = await request({
    url: `${config.uploadUrl}/fileup.php`,
    body: form,
    // onData: bytes => {
    //   console.log('finish: ', bytes, file.size)
    // }
  })
  if (value.zt == 1) {
    context.body = value.text?.[0].f_id; // id
  } else {
    context.status = 500
    context.body = 'fail: 上传失败'
  }
})

export = router
